﻿/******************************************************************************
 * Name         : LSMain.cpp
 * Author       : 671643387
 * Date         : 2015年9月14日
 * Description  :
 *****************************************************************************/

#include <signal.h>
#include <iostream>
#include <dev/base/Runtime.hpp>
#if defined(__WINDOWS__)
#include <common/net/WSAInitialize.hpp>
#endif
#include <common/logger/Logger.hpp>
#include <common/packet/PacketFactoryManager.hpp>
#include "LSMain.hpp"
#include "LoginConnectManager.hpp"
using namespace sxr::login_server;


bool gRunning = true;
void signal_handler(int signal)
{
	switch (signal)
	{
		case SIGINT:
//		case SIGKILL:
			gRunning = false;

    	    sxr::common::getLogger()->log("shuting down server");
        	LoginConnectManager::getMe()->stop();
		break;

		default:
		break;
	}
}

void LSMain(int argc, char* argv[])
{
	__DV_TRY
	{
#if defined(__WINDOWS__)
		sxr::common::WSAInitialize wsaInit;
#endif

		signal(SIGINT, signal_handler);

        dev::base::mtime_t tmStart = dev::base::TimeUtil::fromStartup();
		do
		{
            //// TODO: 注册数据包

			// 初始化登录连接管理器
			if (!LoginConnectManager::getMe()->initialize())
			{
                sxr::common::getLogger()->log("LoginConnectManager::initialize...[FAIL]");
				break;
			}
            sxr::common::getLogger()->log("LoginConnectManager::initialize...[OK]");

			LoginConnectManager::getMe()->start();
		} while (false);
        sxr::common::getLogger()->log("login server is startup after %d ms", dev::base::TimeUtil::fromStartup() - tmStart);

		while (gRunning)
		{
			dev::base::Thread::sleep(500);
		}

		LoginConnectManager::getMe()->join();
		sxr::common::getLogger()->log("LoginConnectManager::stop...[OK]");

		//// 清理资源
		sxr::common::PacketFactoryManager::getMe()->clean();

        sxr::common::getLogger()->log("server is shut down");
	}
	__DV_CATCH(std::exception& e)
	{
		__DV_DUMP(e);
	}
	__DV_CATCH(...)
	{

	}

#if defined(__WINDOWS__)
	std::cout << "press any key to continue" << std::endl;
	std::cin.get();
#endif
}

